package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.PlanService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class PlanController {
	private static final Logger logger = LoggerFactory.getLogger(PlanController.class);

	@Autowired
	private PlanService planService;
	
	/**
	 * 得到计划任务列表信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getLabelName")
	public void getLabelName(ExtPager page,HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		
		HashMap<String,Object> param = new HashMap<String,Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		
		try {
			Object currentCompany = session.getAttribute(WebConstants.CURRENT_COMPANY);
			param.put("company_id",Integer.parseInt(currentCompany.toString()) );
			
			ArrayList<HashMap<String,Object>> logs = planService.getLabelName(param);
			if(logs!=null&&logs.size()>0){
				result.put("success", true);
				result.put("data", logs);
			} else {
				result.put("success", true);
				result.put("data", "");
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	
	/**
	 * 得到数据源信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getDataSource")
	public void getDataSource(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		response.setContentType("text/plain;charset=UTF-8");
		try {
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("company_id",Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString()) );
			ArrayList<HashMap<String,Object>> result = planService.getDataSource(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 新增计划任务
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/insertPlan")
	public void insertPlan(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String type = (String)request.getParameter("type") == null ? null : (String)request.getParameter("type");
		String filePath = (String)request.getParameter("filePath") == null ? null : (String)request.getParameter("filePath");
		String filePath2 = (String)request.getParameter("filePath2") == null ? null : (String)request.getParameter("filePath2");
		String filePath3 = (String)request.getParameter("filePath3") == null ? null : (String)request.getParameter("filePath3");
		String filePath4 = (String)request.getParameter("filePath4") == null ? null : (String)request.getParameter("filePath4");
		String filePath5 = (String)request.getParameter("filePath5") == null ? null : (String)request.getParameter("filePath5");
		String systemMark = (String)request.getParameter("systemMark") == null ? null : (String)request.getParameter("systemMark");
		String planName = (String)request.getParameter("planName") == null ? null : (String)request.getParameter("planName");
		String startDay = (String)request.getParameter("startDay") == null ? null : (String)request.getParameter("startDay");
		String startTime = (String)request.getParameter("startTime") == null ? null : (String)request.getParameter("startTime");
		String setGroup = (String)request.getParameter("setGroup") == null ? null : (String)request.getParameter("setGroup");
		String endDay = (String)request.getParameter("endDay") == null ? null : (String)request.getParameter("endDay");
		String endTime = (String)request.getParameter("endTime") == null ? null : (String)request.getParameter("endTime");
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user!=null){
				HashMap<String,Object> check = planService.checkPlanName(planName);
				if(check==null){
					HashMap<String,Object> param = new HashMap<String,Object>();
					param.put("plan_name", planName);
					param.put("user_id", user.getUserId());
					param.put("create_time", Tools.getCurrentDay());
					param.put("status", 1);
					param.put("company_id",session.getAttribute(WebConstants.CURRENT_COMPANY));
					if(!Tools.isEmpty(startDay)){
						startDay = startDay.substring(0,10);
					}else{
						startDay = "";
					}
					if(!Tools.isEmpty(startTime)){
						startTime = " " + startTime.substring(11);
					}else{
						startTime = "";
					}
					String s_str = startDay + startTime;
					
					if(s_str.equals("")){
						param.put("start_time", "");
					}else{
						param.put("start_time", Tools.getDay(startDay + startTime));
					}
					if(!Tools.isEmpty(endDay)){
						endDay = endDay.substring(0,10);
					}else{
						endDay = "";
					}
					if(!Tools.isEmpty(endTime)){
						endTime = " " + endTime.substring(11);
					}else{
						endTime = "";
					}
					String e_str = endDay + endTime;
					
					if(e_str.equals("")){
						param.put("end_time", "");
					}else{
						param.put("end_time", Tools.getDay(endDay + endTime));
					}
					param.put("type", type);
					if(type.equals("1")){
						param.put("param_str", systemMark);
					} else {
						param.put("param_str", filePath);
						param.put("param_str2", filePath2);
						param.put("param_str3", filePath3);
						param.put("param_str4", filePath4);
						param.put("param_str5", filePath5);
					}
					param.put("loop_type", setGroup);
					int ret = planService.insertPlan(param);
					if(ret == 0){
						result.put("resultcode",0);
					}else{
						result.put("resultcode",9);
					}
				} else {
					result.put("resultcode",1);
				}
			}else{
				result.put("resultcode",9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 得到计划任务列表信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getPlanList")
	public void getCompany(ExtPager page,HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		
		HashMap<String,Object> param = new HashMap<String,Object>();
		HashMap<String,Object> result = new HashMap<String,Object>();
		String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
		response.setContentType("text/plain;charset=UTF-8");
        HashMap<String,Object> orderBy = new HashMap<String,Object>();
		orderBy.put("name", "PLAN_NAME");
		orderBy.put("type", "IMPORT_TYPE");
		orderBy.put("file_path", "PARAM_STR");
		orderBy.put("starttime", "START_TIME");
		orderBy.put("endtime", "END_TIME");
		orderBy.put("loop_type", "LOOP_TYPE");
		orderBy.put("status", "ENABLE");
		orderBy.put("source_name", "PARAM_STR");
		
		try {
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			StringBuffer sort = new StringBuffer("");
			ArrayList<Map<String, String>> field = page.getSortField();
			if(user!=null){
				String cpn_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				
				param.put("cpn_id", cpn_id);
				param.put("pageEnd",page.getStart() + page.getLimit());
				if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
			        	sort.append(orderBy.get(map.get("property")) + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} else {
					param.put("orderBy", " START_TIME");
				}
				param.put("pageStart", page.getStart());
				param.put("subOrder", " order by IMPORT_CODE");
				param.put("language", language);
				ArrayList<HashMap<String,Object>> logs = planService.getPlanList(param);
				if(logs!=null&&logs.size()>0){
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}else{
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 修改计划任务
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updatePlan")
	public void updatePlan(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String type = (String)request.getParameter("type") == null ? null : (String)request.getParameter("type");
		String filePath = (String)request.getParameter("filePath") == null ? null : (String)request.getParameter("filePath");
		String filePath2 = (String)request.getParameter("filePath2") == null ? null : (String)request.getParameter("filePath2");
		String filePath3 = (String)request.getParameter("filePath3") == null ? null : (String)request.getParameter("filePath3");
		String filePath4 = (String)request.getParameter("filePath4") == null ? null : (String)request.getParameter("filePath4");
		String filePath5 = (String)request.getParameter("filePath5") == null ? null : (String)request.getParameter("filePath5");
		String systemMark = (String)request.getParameter("systemMark") == null ? null : (String)request.getParameter("systemMark");
		String planName = (String)request.getParameter("planName") == null ? null : (String)request.getParameter("planName");
		String startDay = (String)request.getParameter("startDay") == null ? null : (String)request.getParameter("startDay");
		String startTime = (String)request.getParameter("startTime") == null ? null : (String)request.getParameter("startTime");
		String setGroup = (String)request.getParameter("setGroup") == null ? null : (String)request.getParameter("setGroup");
		String endDay = (String)request.getParameter("endDay") == null ? null : (String)request.getParameter("endDay");
		String endTime = (String)request.getParameter("endTime") == null ? null : (String)request.getParameter("endTime");
		String id = (String)request.getParameter("id") == null ? null : (String)request.getParameter("id");
		HashMap<String,Object> result = new HashMap<String,Object>();
		int mark = 0;
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
			if(user!=null&&!Tools.isEmpty(id)){
				HashMap<String,Object> check = planService.checkPlanName(planName);
				if(check!=null){
					if((Integer)check.get("id")!=Integer.parseInt(id)){
						mark = 1;
					}
				}
				if(mark == 0){
					HashMap<String,Object> param = new HashMap<String,Object>();
					param.put("plan_name", planName);
					param.put("id", id);
					param.put("company_id",session.getAttribute(WebConstants.CURRENT_COMPANY));
					if(!Tools.isEmpty(startDay)){
						startDay = startDay.substring(0,10);
					}else{
						startDay = "";
					}
					if(!Tools.isEmpty(startTime)){
						startTime = " " + startTime.substring(11);
					}else{
						startTime = "";
					}
					String s_str = startDay + startTime;
					
					if(s_str.equals("")){
						param.put("start_time", "");
					}else{
						param.put("start_time", Tools.getDay(startDay + startTime));
					}
					if(!Tools.isEmpty(endDay)){
						endDay = endDay.substring(0,10);
					}else{
						endDay = "";
					}
					if(!Tools.isEmpty(endTime)){
						endTime = " " + endTime.substring(11);
					}else{
						endTime = "";
					}
					String e_str = endDay + endTime;
					
					if(e_str.equals("")){
						param.put("end_time", "");
					}else{
						param.put("end_time", Tools.getDay(endDay + endTime));
					}
					param.put("type", type);
					if(type.equals("1")){
						param.put("param_str", systemMark);
					} else {
						param.put("param_str", filePath);
						param.put("param_str2", filePath2);
						param.put("param_str3", filePath3);
						param.put("param_str4", filePath4);
						param.put("param_str5", filePath5);
					}
					param.put("loop_type", setGroup);
					int ret = planService.updatePlan(param);
					if(ret == 0){
						result.put("resultcode",0);
					}else{
						result.put("resultcode",9);
					}
				} else {
					result.put("resultcode",1);
				}
			}else{
				result.put("resultcode",9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 批量删除计划任务
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/deletePlan")
	public void deletePlan(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String itemIds = (String)request.getParameter("itemIds") == null ? null : (String)request.getParameter("itemIds");

		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			if(!Tools.isEmpty(itemIds)){
				List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
				String[] ids = itemIds.split(",");	
				HashMap<String,String> map= new HashMap<String,String>();
				HashMap<String, Object> param = new HashMap<String, Object>();
				for(int i=0;i<ids.length;i++){
					map = new HashMap<String,String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				int ret = planService.deletePlan(param);
				if(ret == 0){
					result.put("resultcode",0);
				}else{
					result.put("resultcode",9);
				}
			}else{
				result.put("resultcode",9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 批量开始/结束计划任务
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/startOrStopPlan")
	public void startOrStopPlan(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		String itemIds = (String)request.getParameter("itemIds") == null ? null : (String)request.getParameter("itemIds");
		String status = (String)request.getParameter("status") == null ? null : (String)request.getParameter("status");
		HashMap<String,Object> result = new HashMap<String,Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			if(!Tools.isEmpty(itemIds)){
				List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
				String[] ids = itemIds.split(",");	
				HashMap<String,String> map= new HashMap<String,String>();
				HashMap<String, Object> param = new HashMap<String, Object>();
				for(int i=0;i<ids.length;i++){
					map = new HashMap<String,String>();
					map.put("id", ids[i]);
					list.add(map);
				}
				param.put("list", list);
				param.put("status", status);
				int ret = planService.startOrStopPlan(param);
				if(ret == 0){
					result.put("resultcode",0);
				}else{
					result.put("resultcode",9);
				}
			}else{
				result.put("resultcode",9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 查询计划任务标题
	 * */
	@RequestMapping(value = "/CheckPlanTitle")
	public void CheckPlanTitle(HttpSession session, HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
		try{
			HashMap<String,Object> param = new HashMap<String,Object>();
			param.put("company_id",session.getAttribute(WebConstants.CURRENT_COMPANY));
			ArrayList<HashMap<String,Object>> result = planService.CheckPlanTitle(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		}catch(Exception e){
			logger.error("Exception: ", e);
		}finally{
			writer.flush();
			writer.close();
		}
	}
}
